package com.aiatomic.couting.widgets;

import java.util.ArrayList;
import java.util.List;

import com.aiatomic.couting.MainActivity;
import com.aiatomic.couting.R;
import com.aiatomic.couting.models.TemplateEntity;

import android.content.Context;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;

public class GalleryPagerAdapter extends PagerAdapter {
	private List<TemplateEntity> templates = new ArrayList<TemplateEntity>();
	private Context context;
	private int pagerWidth;

	public GalleryPagerAdapter(Context context, int pagerWidth) {
		super();
		this.context = context;
		this.pagerWidth = pagerWidth;
	}

	public List<TemplateEntity> getTemplates() {
		return templates;
	}

	public void setTemplates(List<TemplateEntity> templates) {
		this.templates = templates;
		// 如果数据大于一条
		if (templates.size() > 1) {
			// 添加最后一页到第一页
			templates.add(0, templates.get(templates.size() - 1));
			// 添加第一页(经过上行的添加已经是第二页了)到最后一页
			templates.add(templates.get(1));
		}
	}

	@Override
	public int getCount() {
		return templates.size();
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		((ViewPager) container).removeView((View) object);
	}

	@Override
	public void setPrimaryItem(ViewGroup container, int position, Object object) {
		super.setPrimaryItem(container, position, object);
		View view = (View) object;
		if (view != null) {
			view.setBackgroundColor(context.getResources().getColor(R.color.green));
			TemplateEntity template = this.getTemplates().get(position);
			((TextView) ((MainActivity) context).findViewById(R.id.current_selected_template))
					.setText(template.getName());
			((MainActivity) context).currentTpl=template;
		}
	}

	@Override
	public Object instantiateItem(ViewGroup view, int position) {
		View templatePageView = View.inflate(context, R.layout.page_template_item, null);
		LayoutParams lp = templatePageView.getLayoutParams();
		if (lp == null) {
			lp = new LayoutParams(pagerWidth, LayoutParams.MATCH_PARENT);
		} else {
			lp.width = pagerWidth;
			lp.height = LayoutParams.MATCH_PARENT;
		}
		templatePageView.setLayoutParams(lp);
		((TextView) templatePageView.findViewById(R.id.txt_template_name)).setText(templates.get(position).getName());
		ImageView img = ((ImageView) templatePageView.findViewById(R.id.img_template_res));
		DownloadImageTask task = new DownloadImageTask(img, R.string.dir_cache_template_store);
		task.execute(templates.get(position).getPic());
		view.addView(templatePageView);
		view.setTag(position);
		return templatePageView;
	}
}
